import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:syn_4s/core/constants/constants.dart';
import 'package:syn_4s/core/extension/build_context_extension.dart';
import 'package:syn_4s/core/extension/int_extension.dart';
import 'package:syn_4s/core/model/map_all_device_model.dart';
import 'package:syn_4s/core/services/google_map_request.dart';
import 'package:syn_4s/core/utils/dialog_utils.dart';
import 'package:syn_4s/core/utils/location_per_utils.dart';
import 'package:syn_4s/core/utils/toast_utils.dart';
import 'package:syn_4s/core/viewmodel/google_map_view_model.dart';
import 'package:syn_4s/core/viewmodel/main_view_model.dart';
import 'package:syn_4s/ui/shared/app_theme.dart';
import 'package:syn_4s/ui/widgets/google_map_watch_dialog.dart';
import 'package:syn_4s/ui/widgets/custom_ui.dart';
import 'package:syn_4s/ui/widgets/google_map_center_dialog.dart';
import 'package:syn_4s/ui/widgets/google_map_lock_dialog.dart';
import 'package:syn_4s/ui/widgets/google_map_monitoring_dialog.dart';

import '../../../core/services/config.dart';
import '../../widgets/main_drawer.dart';

class GoogleMapContent extends StatefulWidget {
  final bool isMainPage;
  final MainViewModel mainViewModel;

  const GoogleMapContent(this.isMainPage, this.mainViewModel,{Key? key});

  @override
  State<GoogleMapContent> createState() => _GoogleMapContentState();
}

class _GoogleMapContentState extends State<GoogleMapContent> {
  late GoogleMapController mapController;
  // final GoogleMapViewModel viewModel = Get.find<GoogleMapViewModel>();
  double latitude = 0;
  double longitude = 0;
  Set<Marker> _marker = {};
  List<MapAllDeviceModel> deviceList = [];
  MapType _mapType = MapType.hybrid;

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        drawer: widget.isMainPage ? null : MainDrawer(),
        appBar: widget.isMainPage
            ? null
            : getAppBar(context.l10n.real_time_location),
        body: buildGoogleMap(),
        floatingActionButton: widget.isMainPage ? null : FloatingActionButton(
            backgroundColor: Colors.white,
            splashColor: Colors.grey,
            mini: true,
            onPressed: (){
              changeMapType();
            },
            child: SvgPicture.asset("assets/images/change_map_type.svg", width: 24.px, height: 24.px),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(30),
            )
        )
    );
  }

  void changeMapType(){
    setState(() {
      _mapType = MapType.hybrid != _mapType ? MapType.hybrid : MapType.terrain;
    });
  }

  Widget buildGoogleMap() {
    return Flex(
      direction: Axis.vertical,
      children: [
        Expanded(
          child: GoogleMap(
            mapType: _mapType,
            zoomControlsEnabled: false,
            myLocationEnabled: false,
            mapToolbarEnabled: false,
            fortyFiveDegreeImageryEnabled: true,
            initialCameraPosition: CameraPosition(target: LatLng(latitude, longitude), zoom: 17.0),
            onMapCreated: (GoogleMapController controller) {
              // 保存控制器引用
              mapController = controller;
              // viewModel.mapController = controller;
              getAllDevice();
            },
            //标记
            markers: _marker,
            onTap: (location) {},
          )
        )
      ],
    );
  }

  void getAllDevice() {
    // MainViewModel mainViewModel = Get.find<MainViewModel>();
    // var deviceTagCodes = mainViewModel.deviceTagCodes;
    GoogleMapRequest.getAllDevice(widget.mainViewModel.deviceTagCodes.toString()).then((result) {
      setState(() {
        if (result.status != HttpConfig.success) {
          ToastUtils.showToast(result.message ?? "");
          return;
        }
        latitude = result!.data![0].lat!;
        longitude = result!.data![0].lng!;
        deviceList = result!.data!;
        setCentralPositioning();
        setMarker();
      });
    }).catchError((error) {
      ToastUtils.showNetError(context);
      print(error.toString());
    });
  }

  void getLocation() {
    determinePosition(context).then((position) {
      // setState(() {
      //   latitude = position.latitude;
      //   longitude = position.longitude;
      //   setCentralPositioning();
      // });
    }).catchError((error) {
      ToastUtils.showNetError(context);
      print(error.toString());
    });
  }

  ///设置地图中心定位
  void setCentralPositioning(){
    mapController.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(target: LatLng(latitude, longitude), zoom: 15.0),
    ));
  }

  void setMarker() {
    // setState(() {
      // print("${widget.mainViewModel.deviceList.length}========================================");
      _marker = deviceList.map((device) => createMarkers(device)).toSet();
    // });
  }

  ///创建标记点
  Marker createMarkers(MapAllDeviceModel device) {
    String icon = "assets/images/${device!.icon}.png";
    return Marker(
        markerId: MarkerId("${device.id}"),
        position: LatLng(device.lat ?? 0, device.lng ?? 0),
        icon: AssetMapBitmap(icon, width: 24.px),
        // infoWindow: InfoWindow(title: device.deviceName),
        onTap: () {
          DialogUtils.loading(context);
          getDeviceDetails(device!.tag!, device!.id!);
        });
  }

  void getDeviceDetails(String tagCode, String id){
    GoogleMapRequest.getDeviceDetails(tagCode, id).then((result){
      DialogUtils.closeDialog(context);
      if (result.status != HttpConfig.success) {
        ToastUtils.showToast(result.message ?? "");
        return;
      }
      print("${result.data?.tag}");
      if(lockTag == result?.data?.tag){
        showLockDialog(result!.data!);
      } else if(watchTag == result?.data?.tag){
        showWatchDialog(result!.data!);
      } else {
        showMonitoringDialog(result!.data!);
      }
    }).catchError((error){
      ToastUtils.showNetError(context);
      DialogUtils.closeDialog(context);
      print(error.toString());
    });
  }

  ///电子锁详情弹框
  void showLockDialog(MapAllDeviceModel data) {
    showModalBottomSheet(
      context: context,
      builder: (context) => GoogleMapLockDialog("SMART LOCK", data),
    );
  }

  ///360检测设备详情弹框
  void showMonitoringDialog(MapAllDeviceModel data) {
    showModalBottomSheet(
      context: context,
      builder: (context) => GoogleMapMonitoringDialog("360 MONITORING PLANT", data),
    );
  }

  ///电子手表详情弹框
  void showWatchDialog(MapAllDeviceModel data) {
    showModalBottomSheet(
      context: context,
      builder: (context) => GoogleMapWatchDialog("SMART WATCH", data),
    );
  }

  ///警报
  void showAlertDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => GoogleMapCenterDialog("DRITICAL ALERTS"),
    );
  }

  @override
  void dispose() {
    super.dispose();
    try {
      mapController.dispose();
    } catch (e) {
      print(e);
    }
  }
}
